/*
 * Fork.java
 * 
 * last update: 16.01.2010 by Stefan Saru
 * 
 * author:	Power(power@kermit.cs.pub.ro)
 * 
 * Obs:
 */

package engine;

/**
 * a fork..join block instance
 */

class Fork extends DefaultInstruction{  
	DefaultInstruction first = null;
	volatile boolean anyThreadStarted;
	ControlThread ctrlTh;
	volatile int count;

	public Fork(NameSpace ns, int delayBefore, InstructionDescription desc,
			DefaultInstruction first, DefaultInstruction next){
		super(ns, delayBefore, desc);
		this.next = next;
		this.first = first;
	}

	public void execute()
	throws InterpretTimeException, SimulationStoppedException
	{
		waitToRun();
		count = 0;
		int k = 0;
		ctrlTh = (ControlThread)Thread.currentThread();
		xConsole.trace(this + "->");
		synchronized (Time.controlThreads) {
			for (Instruction i = first; i != null; i = (Instruction)i.next, k++){
				ControlThread rk = new ForkThread(this, i);
				Time.controlThreads.addElement(rk);
				rk.start();
				xConsole.debug("started: " + i);
			}
			xConsole.debug("fork: " + k + " threads start()-ed");
		}
		while (!anyThreadStarted);
		while (count > 0) ctrlTh.goSleepy();
		xConsole.trace("<-" + this);
	}

	void wakeUp(){
		ctrlTh.wakeUp();
	}
}
